package com.javaweb.interceptor;

import com.javaweb.common.BusinessConstants;
import com.javaweb.controller.common.TokenManager;
import com.javaweb.service.PermService;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/11/5 20:08
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    /**
     *  /article/list,
     *  /article/detail,
     *  /article/edit
     *  /article/add,
     *  /article/delete
     *
     */
    private PermService permService ;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession() ;
        List<String> roleNames = TokenManager.getRolesFromToken(session.getAttribute(BusinessConstants.TOKEN_KEY).toString());
        if (ObjectUtils.isEmpty(roleNames)) {
            return false ;
        }
        List<String> perms = permService.findPermsByRoleName(roleNames) ;
        log.info(" perms: {}", perms) ;
        if (ObjectUtils.isEmpty(perms)) {
            return false ;
        }
        String permUrl = request.getRequestURI();
        log.info("permUrl:{}", permUrl);
        for (String perm : perms) {
            log.info("perm:{}, permUrl:{}, contains:{}", perm,
                    permUrl, permUrl.contains(perm));
            if (permUrl.contains(perm)) {
                return true ;
            }
        }
        // 抛出异常，该异常将被 全局异常Handler统一处理。
        throw new RuntimeException("没有权限访问该资源") ;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
